from django import forms
from .models import UserInfo
from django_redis import get_redis_connection


class UserRegistrationForm(forms.Form):
    username = forms.CharField(max_length=20, min_length=2, error_messages={
        'required': '请传入用户名',
        'max_length': '用户名长度在2-20之间',
        'min_length': '用户名长度在2-20之间',
    })
    email = forms.EmailField(label='邮箱', error_messages={
        'required': '请传入邮箱',
        'invalid': '请传入一个正确的邮箱',
    })
    code = forms.CharField(max_length=4, min_length=4, label='验证码')
    password = forms.CharField(label='密码', max_length=20, min_length=6)

    # 验证邮箱是否唯一
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if UserInfo.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已注册')
        return email

    # 验证验证码是否正确
    def clean_code(self):
        email = self.cleaned_data.get('email')
        if not email:
            raise forms.ValidationError('请先输入有效的邮箱')
        code = self.cleaned_data.get('code')
        # 从缓存中获取验证码
        redis_conn = get_redis_connection()
        cached_code = redis_conn.get(email)
        if cached_code is None:
            raise forms.ValidationError('验证码过期')
        # 如果获取到验证码，进行解码并与用户输入的验证码进行比较
        cached_code = cached_code.decode()  # 安全地进行解码
        if cached_code != code:
            raise forms.ValidationError('验证码错误')

        # 验证通过后可以清除验证码
        redis_conn.delete(email)

        return code

class UserLoginForm(forms.Form):
    email = forms.EmailField(label='邮箱', error_messages={
        'required': '请传入邮箱',
        'invalid': '请传入一个正确的邮箱',
    })
    password = forms.CharField(label='密码', max_length=20, min_length=6)
    rememberMe = forms.IntegerField(required=False)


class PubForm(forms.Form):
    title = forms.CharField(max_length=200, min_length=2)
    content = forms.CharField(min_length=2)
    category = forms.IntegerField()

